import { WEEK_INFO } from '@/constant';
import { showToast, getDevInfo } from '@ray-js/ray';
import Strings from '@/i18n';

export const JsonUtil = {
  parseJSON(str) {
    let rst;
    if (str && {}.toString.call(str) === '[object String]') {
      try {
        rst = JSON.parse(str);
      } catch (e) {
        try {
          // eslint-disable-next-line
          rst = eval(`(${str})`);
        } catch (e2) {
          rst = str;
        }
      }
    } else {
      rst = typeof str === 'undefined' ? {} : str;
    }

    return rst;
  },
};

export const getDevId = () => getDevInfo().devId;

// 星期文本显示
export const weekTextShowHandle = (loops: string) => {
  let str = ''
  let newLoops = loops.padStart(7, '0').split('');
  if (loops === "1111111") {
    return Strings.getLang("dsc_everyday")
  } else if (loops === "0000000") {
    return  Strings.getLang("dsc_once")
  } else {
    newLoops.forEach((item, index) => {
      if (item === "1") {
        str = str + "、" + WEEK_INFO[index]
      }
    })
    return str.slice(1)
  }
}

// 文本弹出框
export const showToastHandle = (val) => {
  showToast({
    title: val,
    icon: 'none',
    duration: 1000,
    mask: true,
  })
}

// 8位切分数组
export function chunkArray(a) {
  const b = [];
  for (let i = 0; i < a.length; i += 8) {
    const chunk = a.slice(i, i + 8);
    b.push(chunk);
  }
  return b;
}

export function toTwoHex(num:string){
  return parseInt(num).toString(16).padStart(2, '0')
}



/**
 * Converts a hexadecimal string to its decimal equivalent
 * @param num - The hexadecimal string to convert
 * @returns The decimal number representation
 */
export function hexToDecimal(num:string){
  return  parseInt(num, 16);
}
export function hexToDecimalTwo(num:string){
  return  parseInt(num, 16).toString().padStart(2, '0');
}

/**
 * 判断字符串是否全部由0组成
 */
export const isAllZeros = (str: string) => {
  return /^0+$/.test(str);
}

//h
export function getCapacitys(uint="ML") {
  const b = [];
  for (let i = 50; i <= 2000; i += 50) {

    b.push(i+ uint);
  }
  return b;
}
export const getWeek = (week) => {
  switch (week) {
    case 1:
      return Strings.getLang("dsc_week_full_mon")
    case 2:
      return Strings.getLang("dsc_week_full_tue")
    case 3:
      return Strings.getLang("dsc_week_full_wed")
    case 4:
      return Strings.getLang("dsc_week_full_thu")
    case 5:
      return Strings.getLang("dsc_week_full_fri")
    case 6:
      return Strings.getLang("dsc_week_full_sat")
    case 0:
      return Strings.getLang("dsc_week_full_sun")
    default:
      break
  }
}
function convertHexTimeToMinutes(timeStr) {
  if (!timeStr || typeof timeStr !== 'string') {
      throw new Error('Invalid input: Expected a string in HH:mm format (hex or decimal)');
  }
  // 分割小时和分钟
  const [hours, minutes] = timeStr.split(':').map(Number);  
  // const hours = parseInt(hoursHex, 16);
  // const minutes = parseInt(minutesHex, 16);
  
  if (
      isNaN(hours) || isNaN(minutes) ||
      hours < 0 || minutes < 0 || minutes >= 60
  ) {
      throw new Error('Invalid hex time format: Expected HH:mm (e.g., "1A:3F")');
  }

  return hours * 60 + minutes;
}
function convertHexTimeToMinutes2(timeStr) {
  if (!timeStr || typeof timeStr !== 'string') {
      throw new Error('Invalid input: Expected a string in HH:mm format (hex or decimal)');
  }
  // 分割小时和分钟
  const hours = parseInt(timeStr.slice(0, 2), 16);
  const minutes = parseInt(timeStr.slice(2, 4), 16);
  
  if (
      isNaN(hours) || isNaN(minutes) ||
      hours < 0 || minutes < 0 || minutes >= 60
  ) {
      throw new Error('Invalid hex time format: Expected HH:mm (e.g., "1A:3F")');
  }

  return hours * 60 + minutes;
}

export function sprintf(str, ...args) {
  let i = 0;
  return str.replace(/%s/g, () => args[i++]);
}
//循环定时冲突判断函数
/**
 * Checks for scheduling conflicts between a new timer and existing cycle timings.
 * @param cycletiming - Array of hex strings representing existing cycle timings (format: XXXXYYYYZZZZ...)
 * @param loops - (Unused in current implementation) String representing loop configuration
 * @param starttimer - Start time of the new timer to check (in decimal)
 * @param endtimer - End time of the new timer to check (in decimal)
 * @param orderNumber - Position indicator ("0" for new timer, otherwise index of existing timer to exclude from check)
 * @returns True if no conflicts found, false if conflicting time ranges detected
 */
export const judgingConflicts = (cycletiming: string[], loops: string, starttimer: string, endtimer: string, orderNumber: number,edit:boolean) => {


  if (cycletiming) {
    let cycleTimingArr = cycletiming
    for (let j = 0; j < cycleTimingArr.length; j++) {
      if (!edit) {
        if (cycleTimingArr[j] && !isAllZeros(cycleTimingArr[j])) {
          let cLoops= parseInt(cycleTimingArr[j].slice(2, 4), 16)
          const curLoops = parseInt(loops, 2);
          // console.log("curLoops:",curLoops,"cLoops",cLoops);
          const cycleStart = convertHexTimeToMinutes2(cycleTimingArr[j].slice(4, 8))
          const cycleEnd = convertHexTimeToMinutes2(cycleTimingArr[j].slice(8, 12))
          const curStart = convertHexTimeToMinutes(starttimer)
          const curEnd = convertHexTimeToMinutes(endtimer)
          // console.log("judgingConflictsTwo1:", j, "cycleStart", cycleStart, "cycleEnd:", cycleEnd, "starttimer: ", curStart, "endtimer:", curEnd)

          if ((curLoops&cLoops)&&!(curStart > cycleEnd || curEnd < cycleStart)) {
            // console.log("judgingConflictsTwo2:", j, "cycleStart", cycleStart, "cycleEnd:", cycleEnd, "starttimer: ", curStart, "endtimer:", curEnd)
            return  {r:false, modeIndex:j}
          }

        }
      } else {
        if (cycleTimingArr[j] &&!isAllZeros(cycleTimingArr[j]) && j !== orderNumber ) {
          // console.log("cycleTimingArr:",cycleTimingArr[j]);

          let cLoops= parseInt(cycleTimingArr[j].slice(2, 4), 16)
          const curLoops = parseInt(loops, 2);
          // console.log("loops:",loops);
          const cycleStart = convertHexTimeToMinutes2(cycleTimingArr[j].slice(4, 8))
          const cycleEnd = convertHexTimeToMinutes2(cycleTimingArr[j].slice(8, 12))
          const curStart = convertHexTimeToMinutes(starttimer)
          const curEnd = convertHexTimeToMinutes(endtimer)
          // console.log("judgingConflictsTwo3:", j, "cycleStart", cycleStart, "cycleEnd:", cycleEnd, "starttimer: ", starttimer, "endtimer:", endtimer,"cLoops",cLoops)

          if ((curLoops&cLoops)&&!(curStart > cycleEnd || curEnd < cycleStart)) {
            // console.log("judgingConflictsTwo4:", j, "cycleStart", cycleStart, "cycleEnd:", cycleEnd, "starttimer: ", starttimer, "endtimer:", endtimer)
            return  {r:false, modeIndex:j}
          }
        }
      }
    }
  }
  return { r: true, modeIndex:-1}
}

// 定时冲突
// export const handleChaos = (timerArr, startTime, loops) => {
//   console.log(timerArr, startTime, loops);
//   const now = new Date()
//   const now_time_sum = now.getHours() * 60 + now.getMinutes()
//   const now_week = now.getDay()
//   const now_week_tomorrow = now_week === 6 ? 0 : now_week + 1
//   const startTime_sum = Number(startTime.slice(0, 2)) * 60 + Number(startTime.slice(3, 5))

//   if (timerArr.length) {
//     timerArr.forEach(item => {
//       const item_starTimer_sum = Number(item.slice(2, 4)) * 60 + Number(item.slice(4, 6))
//       const item_loops = parseInt(item.slice(6, 8), 16).toString(2).padStart(7, '0')

//       if (loops === '0000000') {
//         // 创建或修改的定时为仅一次 
//         if (item.slice(9) === '1') {
//           // 先前的定时为仅一次 只考虑开始时间相等的情况
//           if (startTime_sum === item_starTimer_sum) { return true }
//         } else {
//           // 先前的定时不为仅一次
//           if (now_time_sum >= startTime_sum) {
//             // 明天执行
//             if (startTime_sum === item_starTimer_sum && item_loops.slice(now_week_tomorrow, now_week_tomorrow + 1) === '1') { return true }
//           } else {
//             // 今天执行
//             if (startTime_sum === item_starTimer_sum && item_loops.slice(now_week, now_week + 1) === '1') { return true }
//           }
//         }
//       } else {
//         // 创建或修改的定时为重复或者自定义
//         if (item.slice(9) === '1') {
//           // 先前的定时为仅一次 只考虑开始时间相等的情况
//           if (startTime_sum === item_starTimer_sum) { return true }
//         }else{
//         }
//       }
//     })
//   } return false
// }
